package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.action.UIHelper;
import com.loongtech.bi.entity.flow.AddcashAndConsumeRankModel;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: RechargeRankingFlowNewAction
 * 
 * @Description: 充值排行流水
 * @author liuchen
 * @date 2017-5-17 下午5:47:21
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/rechargeRankingFlow")
public class RechargeRankingFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	/**
	 * 
	 * @Description: TODO 获取参数
	 * @param @param request
	 * @param @param response
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("typeItmes", GameParamConfigManager.getItems(CommonGameParam.CURRENCY_TYPE));
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	protected Date day = new Date(Time.getBeginningOfDay(Time.currentTime() - 1 * Time.DAY));

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> re = new HashMap<String, Object>();
		Map<String, AddcashAndConsumeRankModel> tmpMap = new HashMap<String, AddcashAndConsumeRankModel>();
		List<Object[]> consumeResult = new ArrayList<>();
		List<Object[]> addcashResult = new ArrayList<>();
		List<AddcashAndConsumeRankModel> result = new ArrayList<>();
		try {
			Map<String, Object> m = jsonToMap(params);
			String serverid = (String) m.get("serverid");
			Integer type = Integer.valueOf((String) m.get("type"));

			if (HadoopQueryManager.VISIT_QUEUE.offer("RechargeRankingFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer RechargeRankingFlowNewAction ok!");

				StringBuffer sql1 = new StringBuffer();
				sql1.append("select serverid,userid,sum(wholecashadd) as totalcash from totalroleaddcash where userid != '' and dt = '"
						+ Time.getDateStr(day) + "'");

				if (!"0".equals(serverid)) {
					sql1.append(" and serverid = ");
					sql1.append(serverid);
				}

				sql1.append(" group by serverid,userid order by totalcash desc limit 10000 ");

				Entry<List<String>, List<Object[]>> ret1 = hadoopQueryManager.executeSQL(sql1.toString());
				if (null == ret1 || null == ret1.getKey() || ret1.getKey().isEmpty() || null == ret1.getValue()) {

					re.put("res", "1");
					re.put("msg", "查询结果为空!");
					printToJson(response, re, callback);
					return;
				}

				addcashResult = ret1.getValue();
				// 充值排行
				long addcashIndex = 0;
				// 充值
				for (Object[] obj : addcashResult) {
					AddcashAndConsumeRankModel model = new AddcashAndConsumeRankModel();
					model.setAddcashIndex(++addcashIndex);
					model.setAddcashServerid(String.valueOf(obj[0]));
					model.setAddcashUserid(String.valueOf(obj[1]));
					model.setWholecashadd((long) Double.parseDouble(String.valueOf(obj[2])));
					// 加入
					result.add(model);
				}

				// 消耗查询
				StringBuffer sql2 = new StringBuffer();
				sql2.append("select currencytype,userid,sum(wholeconsume) as totalconsume from totalrolecurrencyconsume where dt = '"
						+ Time.getDateStr(day) + "' ");

				// 增加服务器条件
				if (!"0".equals(serverid)) {
					sql2.append(" and serverid = ");
					sql2.append(serverid);
				}

				// 增加钻石类型条件
				if (type != -99999) {
					sql2.append(" and currencytype = ");
					sql2.append(type);
				}

				sql2.append(" group by currencytype,userid order by totalconsume asc limit 1000 ");

				Entry<List<String>, List<Object[]>> ret2 = hadoopQueryManager.executeSQL(sql2.toString());
				if (null == ret2 || null == ret2.getKey() || ret2.getKey().isEmpty() || null == ret2.getValue()) {
                    re.put("res", new ArrayList<Object[]>());
                    re.put("data", "");
                    printToJson(response, re, callback);
					return;
				}

				consumeResult = ret2.getValue();

				// 消费排行
				long consumeIndex = 0;

				for (Object[] obj : consumeResult) {
					AddcashAndConsumeRankModel model = new AddcashAndConsumeRankModel();
					model.setConsumeIndex(++consumeIndex);
					model.setComnsumeCurrencytype(Integer.parseInt(String.valueOf(obj[0])));
					model.setConsumeUserid(String.valueOf(obj[1]));
					model.setWholeconsume(Long.parseLong(String.valueOf(obj[2])));
					// 存入
					tmpMap.put(String.valueOf(obj[1]), model);
				}

				// 迭代
				for (AddcashAndConsumeRankModel model : result) {
					// 充值的user id
					String addcashUserid = model.getAddcashUserid();
					//
					AddcashAndConsumeRankModel tmpModel = tmpMap.get(addcashUserid);

					if (tmpModel != null) {
						model.setConsumeIndex(tmpModel.getConsumeIndex());
						model.setComnsumeCurrencytype(tmpModel.getComnsumeCurrencytype());
						model.setConsumeUserid(tmpModel.getConsumeUserid());
						model.setWholeconsume(tmpModel.getWholeconsume());
					}
				}

				List<Object[]> lo = new ArrayList<Object[]>();
				for (AddcashAndConsumeRankModel model : result) {
					Object[] o = { model.getAddcashIndex(),
							BiPlatformManager.getServerNameById(model.getAddcashServerid()), model.getAddcashUserid(),
							getMoney(model.getWholecashadd()), model.getConsumeIndex(),
							getMoneyType(model.getComnsumeCurrencytype())  + "(" + model.getComnsumeCurrencytype() + ")", model.getWholeconsume() };
					lo.add(o);
				}
				re.put("res", "0");
				re.put("data", lo);
				printToJson(response, re, callback);
			} else {
				System.out.println("VISIT_QUEUE offer RechargeRankingFlowNewAction failed!");
				re.put("res", "1");
				re.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, re, callback);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			re.put("res", "1");
			re.put("msg", e.getMessage());
			printToJson(response, re, callback);
		}
	}

	private Map<String, String> typeItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.CURRENCY_TYPE); // MoneyTypeManager.reasonItmesRevise;
																														// //
																														// 货币类型反转

	// 元宝类型
	public String getMoneyType(Object currencyType) {
		String key = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";
		return (typeItmesRevise.get(key) == null) ? key : typeItmesRevise.get(key);
	}

	public String getMoney(Long addType) {
		return null != addType ? UIHelper.getYuan(Double.valueOf(addType)) + "" : "";
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
